<template>
  <el-card shadow="never">
    <template #header>
      <div class="flex items-center justify-between">
        <div class="font-medium">帮助手册预览</div>
        <!-- 隐藏的文件输入 -->
        <input
          ref="fileInput"
          type="file"
          style="display: none"
          accept="application/pdf"
          @change="onFileChange"
        />
        <el-button
          v-if="hasPerms('管理员')"
          type="success"
          :disabled="uploading"
          @click="chooseFile"
        >
          {{ uploading ? "上传中..." : "上传帮助手册" }}
        </el-button>
      </div>
    </template>

    <div
      v-if="source"
      v-loading="loading"
      class="h-[calc(100vh-295px)]"
      element-loading-text="加载中..."
    >
      <div class="flex justify-between items-center h-9">
        <div v-if="showAllPages" class="font-medium ml-1.25 text-xl">
          共{{ pageCount }}页
        </div>
        <div v-else>
          <el-pagination
            v-model:current-page="currentPage"
            background
            layout="prev, slot, next"
            :page-size="1"
            :total="pageCount"
          >
            {{ currentPage }} / {{ pageCount }}
          </el-pagination>
        </div>
        <div class="w-[170px] flex-bc">
          <el-checkbox v-model="showAllPages" @change="showAllPagesChange">
            显示所有页面
          </el-checkbox>
          <IconifyIconOnline
            v-tippy="{
              maxWidth: 'none',
              content: `翻转（当前角度${rotations[currentRotation]}度）`
            }"
            icon="ic:baseline-rotate-90-degrees-ccw"
            class="cursor-pointer outline-transparent"
            @click="
              currentRotation === 3
                ? (currentRotation = 0)
                : (currentRotation += 1)
            "
          />
          <IconifyIconOnline
            v-tippy="{
              maxWidth: 'none',
              content: '打印'
            }"
            icon="ri:printer-line"
            class="cursor-pointer outline-transparent"
            @click="onPrint"
          />
        </div>
      </div>
      <el-scrollbar>
        <vue-pdf-embed
          ref="pdfRef"
          class="h-full container overflow-auto"
          :rotation="rotations[currentRotation]"
          :page="currentPage"
          :source="source"
          @rendered="handleDocumentRender"
        />
      </el-scrollbar>
    </div>
    <el-empty
      v-else
      description="说明书暂未上传"
      class="h-full flex justify-center items-center"
    />
  </el-card>
</template>
<script setup lang="ts">
import { ref } from "vue";
import VuePdfEmbed from "vue-pdf-embed";
import { getGlobalManual, uploadGlobalManual } from "@/api/globalConfigApi";
import { message } from "@/utils/message";
import { hasPerms } from "@/utils/auth";

defineOptions({
  name: "Pdf"
});

const pdfRef = ref<any>();
const pageCount = ref(1);
const loading = ref(true);
const currentPage = ref(1);
const currentRotation = ref(0);
const showAllPages = ref(false);
const rotations = [0, 90, 180, 270];

const source = ref<string>("");
const handleDocumentRender = () => {
  loading.value = false;
  pageCount.value = pdfRef.value.doc.numPages;
};

const showAllPagesChange = () => {
  currentPage.value = showAllPages.value ? null : 1;
};

const onPrint = () => {
  // 如果在打印时，打印页面是本身的两倍，在打印配置 页面 设置 仅限页码为奇数的页面 即可
  pdfRef.value.print();
};
const getHelpManual = async () => {
  try {
    const { data } = await getGlobalManual();
    if (data instanceof Blob) {
      const url = URL.createObjectURL(data);
      source.value = url;
    } else {
      message("获取帮助手册失败，请检查服务器是否正常", {
        type: "error"
      });
    }
  } catch (error) {
    console.log(error);
  }
};
getHelpManual();

const fileInput = ref(null);
const uploading = ref(false);

const chooseFile = () => {
  fileInput.value?.click();
};

const onFileChange = async (e: any) => {
  const file = e.target.files?.[0];
  if (!file) return;
  if (file.type !== "application/pdf") {
    message("仅支持上传 PDF 文件", {
      type: "error"
    });
    e.target.value = ""; // 重置选择
    return;
  }
  try {
    uploading.value = true;
    const form = new FormData();
    form.append("file", file);
    const { message: text } = await uploadGlobalManual(form);
    message(text || "上传成功", {
      type: "success"
    });
    e.target.value = "";
    getHelpManual();
  } catch (err) {
    console.error(err);
  } finally {
    uploading.value = false;
  }
};
</script>
